package com.crm.service.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.crm.entity.Department;
import com.crm.repository.DepartmentRepository;
import com.crm.service.DepartmentService;
import com.crm.util.FenyeUtil;
@Service
public class DepartmentServiceImpl implements DepartmentService{

	@Autowired
	private DepartmentRepository depff;
	@Override
	public FenyeUtil<Department> GetMsgByPage(Department dep, Integer page) {
		// TODO Auto-generated method stub
		Pageable pageable = PageRequest.of(page-1, 10);
		Page<Department> pages = depff.findAll(get(dep),pageable);
		FenyeUtil<Department> fenye = new FenyeUtil<>();
		fenye.setCode(0);
		fenye.setData(pages.getContent());
		fenye.setPage((int)pages.getTotalElements());
		return fenye;
	}

	private Specification<Department> get(Department dep) {
		// TODO Auto-generated method stub
		return new Specification<Department>() {
			
			@Override
			public Predicate toPredicate(Root<Department> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				Predicate predicate = criteriaBuilder.conjunction();
				List<Expression<Boolean>> expressions = predicate.getExpressions();
				if(!StringUtils.isEmpty(dep.getBmName())) {
					expressions.add(criteriaBuilder.like(root.get("bmName"),"%"+dep.getBmName()+"%"));
				}
				return predicate;
			}
		};
	}

	@Override
	public String DelDepartment(Integer did) {
		// TODO Auto-generated method stub
		try {
			depff.deleteById(did);
			return "删除成功";
		} catch (Exception e) {
			// TODO: handle exception
			return "删除发生了失败";
		}
	}

	@Override
	public String AddAndUpd(Department d) {
		// TODO Auto-generated method stub
		try {
			depff.saveAndFlush(d);
			return "更新成功";
		} catch (Exception e) {
			return "更新失败";
		}
	}

}
